import request from 'utils/request'
import { apiPrefix } from 'utils/config'

import api from './api'

// 自动导入所有 API 定义文件
const apiFiles = require.context('./', false, /\.js$/)
const apis = apiFiles.keys()
  .filter(key => key !== './index.js') // 排除自己
  .reduce((acc, key) => {
    const module = apiFiles(key)
    return { ...acc, ...(module.default || module) }
  }, {})

api = {...api, ...apis}

const gen = (params) => {
  // let url = apiPrefix + params
  let url = params.trim()
  let method = 'GET'

  const paramsArray = params.split(' ')
  if (paramsArray.length === 2) {
    method = paramsArray[0]
    url = paramsArray[1]
  }

  // 检查拼接完整url地址
  if (!url.startsWith('http')) {
    url = apiPrefix + url
  }

  console.log('url', url)

  return function(data, options) {
    return request({
      url,
      data,
      method,
      ...options
    })
  }
}

const APIFunction = {}
for (const key in api) {
  APIFunction[key] = gen(api[key])
}

APIFunction.queryWeather = params => {
  params.key = 'i7sau1babuzwhycn'
  return request({
    url: `${apiPrefix}/weather/now.json`,
    data: params,
  })
}

export default APIFunction
